<template>
  <div class="signature-canvas">
    <canvas ref="signatureCanvas" :width="canvasWidth" :height="canvasHeight" @mousedown="mousedown"
      @touchstart="touchstart" @mouseup="mouseup" @touchend="touchend" @mousemove="mousemove"
      @touchmove="touchmove"></canvas>
  </div>
</template>
<script lang='ts' setup>
import {
  onMounted, ref, unref
} from 'vue'
import { exportSignature } from '../../utils/config'
const signatureCanvas = ref<HTMLCanvasElement | any>(null)
const compassImg = ref();
const ctx = ref<CanvasText | any>(null)
const isDrawing = ref<Boolean>(false)

const emits = defineEmits(['getSignature'])
const props = defineProps({
  canvasImg: {
    type: String,
    require: true,
  },
  canvasWidth: {
    type: String,
    default: '600'
  },
  canvasHeight: {
    type: String,
    default: '300'
  }
})
// 初始化
const initCanvas = () => {
  ctx.value = unref(signatureCanvas)!.getContext('2d')
  ctx.value.strokeStyle = '#000000';  // 设置默认黑色笔迹
  ctx.value.lineWidth = 2;            // 定义基础线条粗细
  ctx.value.lineJoin = 'round';        // 优化线条连接处平滑度
  ctx.value.lineCap = 'round';         // 消除笔触末端毛刺
}

// 鼠标按下
const mousedown = (e: MouseEvent) => {
  isDrawing.value = true;
  ctx.value.moveTo(e.offsetX, e.offsetY);
  ctx.value.beginPath();
}
const touchstart = (e: TouchEvent) => {
  isDrawing.value = true;
  const pos = getCanvasPosition(e.touches[0].clientX, e.touches[0].clientY);
  ctx.value.moveTo(pos.x, pos.y);
  ctx.value.beginPath();
}
// 鼠标抬起
const mouseup = () => {
  isDrawing.value = false
}
const touchend = () => {
  isDrawing.value = false
}
const setSignature = () => {
  emits('getSignature', exportSignature(unref(signatureCanvas)!))
}
// 鼠标拖动
const mousemove = (e: MouseEvent) => {
  if (!unref(isDrawing)) return;
  ctx.value.lineTo(e.offsetX, e.offsetY);
  ctx.value.stroke();
  setSignature()
}
const touchmove = (e: TouchEvent) => {
  e.preventDefault();
  if (!unref(isDrawing)) return;
  const pos = getCanvasPosition(e.touches[0].clientX, e.touches[0].clientY)
  ctx.value.lineTo(pos.x, pos.y)
  ctx.value.stroke();
  setSignature()
}

// 统一坐标转换方法
const getCanvasPosition = (clientX: number, clientY: number) => {
  const rect = signatureCanvas.value!.getBoundingClientRect()
  return {
    x: (clientX - rect.left) * (signatureCanvas.value!.width / rect.width),
    y: (clientY - rect.top) * (signatureCanvas.value!.height / rect.height)
  }
}

onMounted(() => {
  initCanvas()
})
</script>
<style lang='less' scoped>
.signature-canvas {
  display: inline-block;
  margin: 20px;
  border: 1px dotted #ccc;
}
</style>